package com.dmagic.cms.service.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dmagic.cms.common.dao.CommonDao;
import com.dmagic.cms.common.exception.ServiceException;
import com.dmagic.cms.common.exception.ValidateException;
import com.dmagic.cms.common.query.PageUtil;
import com.dmagic.cms.common.service.CommonService;
import com.dmagic.cms.common.util.StringUtil;
import com.dmagic.cms.dao.ProductDao;
import com.dmagic.cms.entity.LinkedHeatMap;
import com.dmagic.cms.entity.Product;
import com.dmagic.cms.service.HeatMapService;
import com.dmagic.cms.service.ProductService;

@Service
@Transactional(readOnly = true)
public class ProductServiceImpl extends CommonService<Product> implements ProductService {
	@Autowired
	private ProductDao productDao;

	@Autowired
	private HeatMapService heatMapService;

	@Override
	protected CommonDao<Product, Serializable> getCommonDao() {
		return (CommonDao) productDao;
	}

	@Override
	@Transactional(readOnly = false)
	public void saveProduct(Product[] product) throws ValidateException {
		for (Product p : product) {
			if (StringUtil.isBlank(p.getProductName()) && StringUtil.isBlank(p.getProductContent())) {
				continue;
			}
			if (p.getIsTop() == null) {
				p.setIsTop(false);
			}
			if (p.getProductStatus() == null) {
				p.setProductStatus(false);
			}
			saveEntity(p);
		}
	}

	@Override
	public void searchProduct(PageUtil<Map> pageUtil) throws ServiceException {
		try {
			productDao.searchProduct(pageUtil);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}

	@Override
	public Product getProduct(Long productId) throws ServiceException {
		return getEntityById(productId);
	}

	public List<Product> getProductByProductNo(String productNo) {
		return productDao.findBy("productNo", productNo);
	}

	@Override
	@Transactional(readOnly = false)
	public void deleteProduct(List<Long> productIds) throws ServiceException {
		for (Long productId : productIds) {
			deleteProduct(productId);
		}
	}

	@Override
	@Transactional(readOnly = false)
	public void deleteProduct(Long productId) throws ServiceException {
		deleteEntityById(productId);
		heatMapService.deleteLinkedHeatMapByLinkedIdAndType(productId,
				LinkedHeatMap.HeatMapType.product.getValue());
	}

	@Override
	@Transactional(readOnly = false)
	public void changeProductCategory(List<Long> productIds, Long productCategoryId) throws ServiceException {
		for (Long productId : productIds) {
			Product product = getProduct(productId);
			product.setProductCategoryId(productCategoryId);
			saveEntity(product);
		}
	}
}
